﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Security.Cryptography;
using Inovout.Organization.Membership.Domain;
using NHibernate;
using Inovout.Organization.Domain;
using System.Web;
using NHibernate.Criterion;
using Inovout.Data.Service;
using Inovout.Component;
using System.Configuration;
using KuaJing.LaiBa.ManageMentConsole.Service_263;
using KuaJing.LaiBa.ManageMentConsole.Models;

namespace KuaJing.LaiBa.ManageMentConsole.Service
{
    public class DepartmentLogic : RepositoryService<OrganizationUnit>
    {
        private readonly string userid = "jiw";
        private readonly string key = "uieHDj93Wx";
        private readonly string domain = "samples.cn";
        private readonly string account = "samples.cn";
        public DepartmentLogic()
        {
        }
        /// <summary>
        /// 引用WebService，读取部门信息
        /// </summary>
        /// <returns></returns>
        public List<Department> GetDepartment()
        {
            XmapiImplService service = new XmapiImplService();
            string sign = Md5Sign(userid + domain + account + key);
            string str = service.getDepartment(userid, domain, account, sign);
            XDocument Doc = XDocument.Parse(str);

            List<Department> departments = new List<Department>();
            var query1 = (from item in Doc.Descendants("department")
                          select BuidOrg(item)).ToList();
            var query = (from item in Doc.Descendants("department")
                         select new
                         {
                             departmentId = item.Element("departmentId").Value,
                             domainId = item.Element("domainId").Value,
                             departmentName = item.Element("departmentName").Value,
                             description = item.Element("description") == null ? null : item.Element("description").Value,
                             depId = item.Element("depId").Value,
                             rank = item.Element("rank") == null ? null : item.Element("rank").Value,
                             type = item.Element("type") == null ? null : item.Element("type").Value,
                             top = item.Element("top").Value,
                             resv1 = item.Element("resv1") == null ? null : item.Element("resv1").Value,
                             resv2 = item.Element("resv2") == null ? null : item.Element("resv2").Value
                         }).ToList();
            foreach (var item in query)
            {
                Department department = new Department();
                department.departmentId = item.departmentId;
                department.domainId = item.domainId;
                department.departmentName = item.departmentName;
                department.description = item.description;
                department.depId = item.depId;
                department.rank = item.rank;
                department.type = item.type;
                department.top = item.top;
                department.resv1 = item.resv1;
                department.resv2 = item.resv2;
                departments.Add(department);
            }
            Department det = departments.Where(c => c.departmentId == "307").Select(c => c).SingleOrDefault();
            List<Department> des = new List<Department>();
            des = GetDataDepartment(det, des, departments);
            des.Add(det);
            return des;
        }
        private Department BuidOrg(XElement node)
        {
            return new Department();
        }
        public List<Department> GetDataDepartment(Department des, List<Department> newdes, List<Department> departs)
        {
            List<Department> departments = departs.Where(c => c.depId == des.departmentId).Select(c => c).ToList();
            foreach (Department depart in departments)
            {
                newdes.Add(depart);
                GetDataDepartment(depart, newdes, departs);
            }
            return newdes;
        }
        /// <summary>
        /// 32位 小写 MD5 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string Md5Sign(string str)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] buffer = Encoding.Default.GetBytes(str);
            string result = BitConverter.ToString(md5.ComputeHash(buffer));
            return result.Replace("-", "").ToLower();
        }
        public void Handle()
        {
            try
            {
                List<Department> departments = GetDepartment();
                List<OrganizationUnit> Units = GetAllDepaetment();
                foreach (Department department in departments)
                {
                    if (Units.Count() == 0)
                    {
                        OrganizationUnit ships = new OrganizationUnit(department.departmentName, department.departmentId, department.depId);
                        InsertDepaetment(ships);
                    }
                    else
                    {
                        //OrganizationUnit ship = GetDepaetment(department.departmentId);
                        OrganizationUnit ship = Units.Where(c => c.DepartmentId.Equals(department.departmentId)).Select(c => c).SingleOrDefault();
                        if (ship == null)
                        {
                            ship = new OrganizationUnit(department.departmentName, department.departmentId, department.depId);
                            InsertDepaetment(ship);
                        }
                        else
                        {
                            Units.Remove(ship);
                            ship.DepartmentId = department.departmentId;
                            ship.Name = department.departmentName;
                            ship.DepId = department.depId;
                            InsertDepaetment(ship);
                        }
                    }
                }
                RemoveAllDepaetment(Units);
                PersonLogic personlogic = new PersonLogic();
                personlogic.Handle();
            }
            catch (Exception e)
            {
                string str = e.Message;
            }
        }
        public List<Department> GetDepartment(string url)
        {
            XDocument Doc = XDocument.Load(url);
            List<Department> departments = new List<Department>();
            var query = (from item in Doc.Descendants("department")
                         select new
                         {
                             departmentId = item.Element("departmentId").Value,
                             name = item.Element("name").Value,
                             domainId = item.Element("domainId").Value,
                             departmentName = item.Element("departmentName").Value,
                             description = item.Element("description").Value,
                             depId = item.Element("depId").Value,
                             rank = item.Element("rank").Value,
                             type = item.Element("type").Value,
                             top = item.Element("top").Value,
                             resv1 = item.Element("resv1").Value,
                             resv2 = item.Element("resv2").Value
                         }).ToList();
            foreach (var item in query)
            {
                Department department = new Department();
                department.departmentId = item.departmentId;
                department.name = item.name;
                department.domainId = item.domainId;
                department.departmentName = item.departmentName;
                department.description = item.description;
                department.depId = item.depId;
                department.rank = item.rank;
                department.type = item.type;
                department.top = item.top;
                department.resv1 = item.resv1;
                department.resv2 = item.resv2;
                departments.Add(department);
            }
            return departments;
        }

        /// <summary>
        /// 查询部门
        /// </summary>
        /// <param name="departmentid"></param>
        /// <returns></returns>
        public OrganizationUnit GetDepaetment(string departmentid)
        {
            string str = departmentid;
            IRepositoryService<OrganizationUnit> Service = ComponentRegistry.Resolve<IRepositoryService<OrganizationUnit>>();
            OrganizationUnit unit = Service.Query().SingleOrDefault(c => c.DepartmentId.Equals(str));
            return unit;
        }
        public void InsertDepaetment(OrganizationUnit Unit)
        {
            IRepositoryService<OrganizationUnit> Service = ComponentRegistry.Resolve<IRepositoryService<OrganizationUnit>>();
            Service.Save(Unit);
        }
        public void UpdateDepartment(OrganizationUnit Unit)
        {
            IRepositoryService<OrganizationUnit> Service = ComponentRegistry.Resolve<IRepositoryService<OrganizationUnit>>();
            Update(Unit);
        }
        public List<OrganizationUnit> GetAllDepaetment()
        {
            IRepositoryService<OrganizationUnit> Service = ComponentRegistry.Resolve<IRepositoryService<OrganizationUnit>>();
            IQueryable<OrganizationUnit> Units = Service.Query();
            return Units == null ? null : Units.ToList();
        }
        public void RemoveAllDepaetment(List<OrganizationUnit> Units)
        {
            IRepositoryService<OrganizationUnit> Service = ComponentRegistry.Resolve<IRepositoryService<OrganizationUnit>>();
            foreach (OrganizationUnit unit in Units)
            {
                Service.Delete(unit);
            }
        }
    }
}
